package com.lql.sort;

import java.util.Arrays;
import java.util.Random;

/**
 * 冒泡排序
 */
public class BubbleSort {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 1, 7};
        int[] ints = new int[8000];
        Random random = new Random();
        for (int i = 0; i < 8000; i++) {
            ints[i] = random.nextInt(8000);
        }
        System.out.println(Arrays.toString(bubbleSorted(array)));
    }

    /**
     * 冒泡排序
     *
     * @param arrays 待排序的数组
     */
    public static int[] bubbleSorted(int[] arrays) {
        int temp;
        //定义标志位进行优化，当数组元素不再发生交换时，停止比较
        boolean flag = false;
        long startTime = System.currentTimeMillis();
        System.out.println("开始：" + startTime);
        for (int i = 0; i < arrays.length - 1; i++) {
            for (int j = 0; j < arrays.length - 1 - i; j++) {
                if (arrays[j] > arrays[j + 1]) {
                    flag = true;
                    temp = arrays[j + 1];
                    arrays[j + 1] = arrays[j];
                    arrays[j] = temp;
                }
            }
            if (!flag) {
                // 未发生交换直接跳出循环
                break;
            } else {
                // 发生交换,重新将flag设置为false
                flag = false;
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("结束：" + endTime);
        float l = (endTime - startTime) / 1000f;
        System.err.println("总时间：" + l + "秒");
        return arrays;
    }

}
